<template>
  <div class="user-center" ref="userCenterContainer">
    <!-- 未登录时访问自己主页的提示 -->
    <div v-if="isAccessingOwnProfileWhileLoggedOut" class="login-required-overlay">
      <div class="login-prompt">
        <div class="prompt-icon">👤</div>
        <h2>请先登录</h2>
        <p>您需要登录后才能访问个人主页</p>
        <a-button type="primary" size="large" @click="handleOpenLogin">立即登录</a-button>
      </div>
    </div>
    
    <div class="user-layout" v-else>
      <!-- 左侧边栏 -->
      <div class="user-sidebar">
        <div class="sidebar-content">
          <!-- 用户基本信息 -->
          <div class="user-profile-card">
            <div class="profile-header">
              <a-avatar :size="80" :src="userProfile.avatar ? getImageUrl(userProfile.avatar) : ''" :style="{ fontSize: '28px' }">
                {{ userProfile.username?.charAt(0)?.toUpperCase() || 'U' }}
              </a-avatar>
              <h3 class="profile-username">{{ userProfile.username || '未知用户' }}</h3>
            </div>

            <!-- 个人介绍单独一行 -->
            <div class="profile-bio-section" v-if="userProfile.bio">
              <p class="profile-bio">{{ userProfile.bio }}</p>
            </div>

            <!-- 统计信息 -->
            <div class="profile-stats">
              <div class="stat-item">
                <span class="stat-number">{{ userStats.articleCount || 0 }}</span>
                <span class="stat-label">文章</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ followStats.followersCount || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ followStats.followingCount || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>

            <!-- 关注按钮 -->
            <div class="profile-actions" v-if="!isOwnProfile">
              <a-button :type="followStatus.isFollowing ? 'default' : 'primary'" :loading="followLoading" @click="handleFollowToggle" block>
                {{ followStatus.isFollowing ? '已关注' : '关注' }}
              </a-button>
            </div>

            <!-- 编辑按钮 -->
            <div class="profile-actions" v-if="isOwnProfile">
              <a-button type="primary" @click="handleWriteArticle" :icon="h(EditOutlined)" style="margin-top: 8px" block> 写文章 </a-button>
            </div>
          </div>

          <!-- 导航菜单 -->
          <div class="sidebar-menu">
            <a-menu v-model:selectedKeys="selectedMenuKeys" mode="vertical" @select="handleMenuSelect" :style="{ border: 'none' }">
              <a-menu-item key="profile">
                <template #icon><user-outlined /></template>
                {{ isOwnProfile ? '个人资料' : 'Ta的资料' }}
              </a-menu-item>
              <a-menu-item key="articles">
                <template #icon><file-text-outlined /></template>
                {{ isOwnProfile ? '文章' : 'Ta的文章' }} ({{ userStats.articleCount || 0 }})
              </a-menu-item>
              <a-menu-item key="favorites" v-if="isOwnProfile">
                <template #icon><star-outlined /></template>
                收藏 ({{ userStats.favoriteCount || 0 }})
              </a-menu-item>
              <a-menu-item key="followers">
                <template #icon><team-outlined /></template>
                {{ isOwnProfile ? '粉丝列表' : 'Ta的粉丝' }} ({{ followStats.followersCount || 0 }})
              </a-menu-item>
              <a-menu-item key="following">
                <template #icon><user-add-outlined /></template>
                {{ isOwnProfile ? '关注列表' : 'Ta的关注' }} ({{ followStats.followingCount || 0 }})
              </a-menu-item>
              <a-menu-item key="notifications" v-if="isOwnProfile">
                <template #icon><bell-outlined /></template>
                消息通知
                <a-badge v-if="unreadCount > 0" :count="unreadCount" size="small" style="margin-left: 8px" />
              </a-menu-item>
            </a-menu>
          </div>
        </div>
      </div>

      <!-- 右侧主内容 -->
      <div class="user-main-content">
        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 个人资料 -->
          <div v-if="activeView === 'profile'" class="view-content">
            <div class="about-section">
              <!-- 个人资料卡片 -->
              <div class="profile-card">
                <div class="profile-card-header">
                  <h3 class="profile-card-title">{{ isOwnProfile ? '个人资料' : `${userProfile.username || 'Ta'}的资料` }}</h3>
                  <div v-if="isOwnProfile" class="profile-card-actions">
                    <a-button type="link" size="small" @click="toggleEditMode">
                      <template #icon><edit-outlined v-if="!isEditing" /><save-outlined v-if="isEditing" /></template>
                      {{ isEditing ? '保存' : '编辑' }}
                    </a-button>
                    <a-button v-if="isEditing" type="link" size="small" @click="cancelEdit" style="margin-left: 8px"> 取消 </a-button>
                  </div>
                </div>
                <div class="profile-card-content">
                  <!-- 查看模式 -->
                  <div v-if="!isEditing" class="profile-content">
                    <!-- 头像和基本信息 -->
                    <div class="profile-header">
                      <a-avatar :size="80" :src="userProfile.avatar ? getImageUrl(userProfile.avatar) : ''" class="profile-avatar" :style="{ fontSize: '28px' }">
                        {{ userProfile.username?.charAt(0)?.toUpperCase() || 'U' }}
                      </a-avatar>
                      <div class="profile-basic">
                        <h3 class="profile-name">{{ userProfile.username || '未设置用户名' }}</h3>
                        <p class="profile-email" v-if="userProfile.email">{{ userProfile.email }}</p>
                        <p class="profile-join-date">{{ formatDate(userProfile.created_at) }} 加入</p>
                      </div>
                    </div>

                    <!-- 职业信息 -->
                    <div class="profile-work" v-if="hasWorkInfo || isEditing">
                      <div class="section-divider">职业信息</div>
                      <div class="work-info-grid">
                        <div v-if="userProfile.career_direction" class="work-info-item">
                          <span class="work-label">职业方向：</span>
                          <span class="work-value career-tag">{{ userProfile.career_direction }}</span>
                        </div>
                        <div v-if="userProfile.position" class="work-info-item">
                          <span class="work-label">职位：</span>
                          <span class="work-value">{{ userProfile.position }}</span>
                        </div>
                        <div v-if="userProfile.company" class="work-info-item">
                          <span class="work-label">公司：</span>
                          <span class="work-value">{{ userProfile.company }}</span>
                        </div>
                        <div v-if="userProfile.work_start_date" class="work-info-item">
                          <span class="work-label">开始工作：</span>
                          <span class="work-value">{{ formatDate(userProfile.work_start_date) }}</span>
                        </div>
                      </div>
                    </div>

                    <!-- 个人介绍 -->
                    <div class="profile-bio-section" v-if="userProfile.bio">
                      <div class="section-divider">个人介绍</div>
                      <p class="bio-content">{{ userProfile.bio }}</p>
                    </div>

                    <!-- 兴趣标签 -->
                    <div class="profile-interests" v-if="userProfile.interest_tags && userProfile.interest_tags.length > 0">
                      <div class="section-divider">兴趣标签</div>
                      <div class="interest-tags">
                        <span v-for="tag in userProfile.interest_tags" :key="tag" class="interest-tag">
                          {{ tag }}
                        </span>
                      </div>
                    </div>

                    <!-- 空状态提示 -->
                    <div v-if="!hasAnyProfile && isOwnProfile" class="empty-profile">
                      <div class="empty-state-content">
                        <div class="empty-icon">📝</div>
                        <p class="empty-text">还没有完善个人资料</p>
                        <a-button type="primary" @click="toggleEditMode">立即完善</a-button>
                      </div>
                    </div>
                  </div>

                  <!-- 编辑模式 -->
                  <div v-else class="profile-edit-form">
                    <a-form :model="editForm" layout="vertical" @finish="saveProfile">
                      <!-- 基本信息 -->
                      <div class="section-divider">基本信息</div>

                      <!-- 头像上传 -->
                      <a-row :gutter="16">
                        <a-col :span="24">
                          <a-form-item label="头像">
                            <div class="avatar-upload-container">
                              <a-upload :before-upload="handleAvatarUpload" :show-upload-list="false" accept="image/*" class="avatar-uploader">
                                <div class="avatar-upload-area">
                                  <a-avatar :size="80" :src="editForm.avatar ? getImageUrl(editForm.avatar) : ''" :style="{ fontSize: '28px' }">
                                    {{ editForm.username?.charAt(0)?.toUpperCase() || 'U' }}
                                  </a-avatar>
                                  <div class="upload-overlay">
                                    <upload-outlined />
                                    <div class="upload-text">点击上传</div>
                                  </div>
                                </div>
                              </a-upload>
                              <div class="avatar-actions">
                                <a-button v-if="editForm.avatar" type="link" @click="removeAvatar" size="small">删除头像</a-button>
                              </div>
                            </div>
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <a-row :gutter="16">
                        <a-col :span="24">
                          <a-form-item label="用户名">
                            <a-input v-model:value="editForm.username" placeholder="请输入用户名" />
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <a-row :gutter="16">
                        <a-col :span="24">
                          <a-form-item label="个人介绍">
                            <a-textarea v-model:value="editForm.bio" placeholder="介绍一下自己吧..." :rows="4" :maxlength="200" show-count />
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <!-- 职业信息 -->
                      <div class="section-divider">职业信息</div>

                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="职业方向">
                            <a-select v-model:value="editForm.career_direction" placeholder="选择职业方向" allowClear>
                              <a-select-option value="前端开发">前端开发</a-select-option>
                              <a-select-option value="后端开发">后端开发</a-select-option>
                              <a-select-option value="全栈开发">全栈开发</a-select-option>
                              <a-select-option value="移动开发">移动开发</a-select-option>
                              <a-select-option value="数据科学">数据科学</a-select-option>
                              <a-select-option value="AI/机器学习">AI/机器学习</a-select-option>
                              <a-select-option value="产品经理">产品经理</a-select-option>
                              <a-select-option value="UI/UX设计">UI/UX设计</a-select-option>
                              <a-select-option value="测试工程师">测试工程师</a-select-option>
                              <a-select-option value="运维工程师">运维工程师</a-select-option>
                              <a-select-option value="其他">其他</a-select-option>
                            </a-select>
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="职位">
                            <a-input v-model:value="editForm.position" placeholder="请输入职位" />
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="公司">
                            <a-input v-model:value="editForm.company" placeholder="请输入公司名称" />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="开始工作时间">
                            <a-date-picker v-model:value="editForm.work_start_date" placeholder="选择开始工作时间" style="width: 100%" />
                          </a-form-item>
                        </a-col>
                      </a-row>

                      <!-- 兴趣标签 -->
                      <div class="section-divider">兴趣标签</div>
                      <a-form-item label="兴趣标签">
                        <a-select v-model:value="editForm.interest_tags" mode="tags" placeholder="添加你的兴趣标签" :max-tag-count="10" style="width: 100%">
                          <a-select-option value="JavaScript">JavaScript</a-select-option>
                          <a-select-option value="Vue.js">Vue.js</a-select-option>
                          <a-select-option value="React">React</a-select-option>
                          <a-select-option value="Node.js">Node.js</a-select-option>
                          <a-select-option value="Python">Python</a-select-option>
                          <a-select-option value="Java">Java</a-select-option>
                          <a-select-option value="设计">设计</a-select-option>
                          <a-select-option value="摄影">摄影</a-select-option>
                          <a-select-option value="旅行">旅行</a-select-option>
                          <a-select-option value="音乐">音乐</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-form>
                  </div>
                </div>
              </div>

              <div class="stats-card">
                <div class="stats-card-header">
                  <h3 class="stats-card-title">数据统计</h3>
                </div>
                <div class="stats-card-content">
                  <a-row :gutter="16">
                    <a-col :span="6">
                      <a-statistic title="发布文章" :value="userStats.articleCount || 0" />
                    </a-col>
                    <a-col :span="6">
                      <a-statistic title="总阅读量" :value="userStats.totalViews || 0" />
                    </a-col>
                    <a-col :span="6">
                      <a-statistic title="获得点赞" :value="userStats.totalLikes || 0" />
                    </a-col>
                    <a-col :span="6">
                      <a-statistic title="粉丝数量" :value="followStats.followersCount || 0" />
                    </a-col>
                  </a-row>
                </div>
              </div>
            </div>
            <!-- 数据统计图表 -->
            <UserStatsChart :user-stats="userStats" :loading="false" />
          </div>

          <!-- 文章列表 -->
          <div v-if="activeView === 'articles'" class="view-content">
            <!-- 文章列表头部 -->
            <div class="list-header">
              <h3>{{ isOwnProfile ? '我的文章' : `${userProfile.username || 'Ta'}的文章` }}</h3>
              <div class="list-actions" v-if="isOwnProfile">
                <a-button type="primary" @click="handleWriteArticle" :icon="h(EditOutlined)">写文章</a-button>
              </div>
            </div>

            <a-spin :spinning="articlesLoading">
              <div v-if="articles.length === 0 && !articlesLoading" class="empty-state">
                <a-empty description="暂无文章">
                  <template #image>
                    <file-text-outlined style="font-size: 64px; color: #d9d9d9" />
                  </template>
                  <a-button v-if="isOwnProfile" type="primary" @click="handleWriteArticle"> 发表第一篇文章 </a-button>
                </a-empty>
              </div>
              <div v-else class="article-list">
                <article v-for="article in articles" :key="article.id" class="article-item">
                  <!-- 文章主要内容 -->
                  <div class="article-main">
                    <!-- 文章标题 -->
                    <h2 class="article-title" @click="handleArticleClick(article.id)">
                      <span v-if="article.is_recommended" class="recommend-badge">推荐</span>
                      {{ article.title }}
                    </h2>

                    <!-- 文章摘要 -->
                    <div class="article-abstract" @click="handleArticleClick(article.id)">
                      {{ article.summary || '暂无摘要' }}
                    </div>

                    <!-- 标签 -->
                    <div class="article-tags" v-if="article.tags && article.tags.length > 0">
                      <a-tag v-for="tag in article.tags.slice(0, 3)" :key="tag" size="small" class="article-tag">
                        {{ tag }}
                      </a-tag>
                      <span v-if="article.tags.length > 3" class="more-tags"> +{{ article.tags.length - 3 }} </span>
                    </div>

                    <!-- 文章元信息 -->
                    <div class="article-meta">
                      <div class="author-info">
                        <AuthorHover :authorId="article.author_id || userId" :authorName="article.author_name" :authorAvatar="article.author_avatar" :size="25" />
                        <span class="author-name">{{ article.author_name }}</span>

                        <div class="article-stats">
                          <span class="stat-item" title="阅读量">
                            <eye-outlined />
                            {{ formatNumber(article.view_count) }}
                          </span>
                          <span class="stat-item" title="点赞数">
                            <like-outlined />
                            {{ formatNumber(article.like_count) }}
                          </span>
                          <span class="stat-item" title="评论数">
                            <message-outlined />
                            {{ formatNumber(article.comment_count) }}
                          </span>
                        </div>
                      </div>
                      <time class="article-time">
                        {{ article.created_at }}
                      </time>
                    </div>
                  </div>

                  <!-- 文章封面 -->
                  <div class="article-cover" v-if="article.cover_image">
                    <img :src="getImageUrl(article.cover_image)" :alt="article.title" />
                  </div>
                </article>
              </div>
            </a-spin>

            <!-- 加载更多状态 -->
            <div class="load-more-status" v-if="articles.length > 0">
              <div v-if="articlesLoadingMore" class="loading-more">
                <a-spin size="small" />
                <span>加载中...</span>
              </div>
              <div v-else-if="!articlesPagination.hasNext" class="no-more">
                <span>没有更多文章了</span>
                <div class="total-info">共 {{ articlesPagination.total }} 篇文章</div>
              </div>
            </div>
          </div>

          <!-- 收藏列表 -->
          <div v-if="activeView === 'favorites'" class="view-content">
            <!-- 收藏列表头部 -->
            <div class="list-header">
              <h3>{{ isOwnProfile ? '我的收藏' : `${userProfile.username || 'Ta'}的收藏` }}</h3>
              <div class="list-actions" v-if="isOwnProfile">
                <a-button type="default" @click="refreshFavorites" :icon="h(ReloadOutlined)">刷新</a-button>
              </div>
            </div>

            <a-spin :spinning="favoritesLoading">
              <div v-if="favorites.length === 0 && !favoritesLoading" class="empty-state">
                <a-empty description="暂无收藏">
                  <template #image>
                    <star-outlined style="font-size: 64px; color: #d9d9d9" />
                  </template>
                </a-empty>
              </div>
              <div v-else class="article-list">
                <article v-for="article in favorites" :key="article.id" class="article-item">
                  <!-- 与文章列表相同的结构 -->
                  <div class="article-main">
                    <h2 class="article-title" @click="handleArticleClick(article.id)">
                      <span v-if="article.is_recommended" class="recommend-badge">推荐</span>
                      {{ article.title }}
                    </h2>
                    <div class="article-abstract" @click="handleArticleClick(article.id)">
                      {{ article.summary || '暂无摘要' }}
                    </div>
                    <div class="article-tags" v-if="article.tags && article.tags.length > 0">
                      <a-tag v-for="tag in article.tags.slice(0, 3)" :key="tag" size="small" class="article-tag">
                        {{ tag }}
                      </a-tag>
                      <span v-if="article.tags.length > 3" class="more-tags"> +{{ article.tags.length - 3 }} </span>
                    </div>
                    <div class="article-meta">
                      <div class="author-info">
                        <AuthorHover :authorId="article.author_id" :authorName="article.author_name" :authorAvatar="article.author_avatar" :size="25" />
                        <span class="author-name">{{ article.author_name }}</span>
                        <div class="article-stats">
                          <span class="stat-item" title="阅读量">
                            <eye-outlined />
                            {{ formatNumber(article.view_count) }}
                          </span>
                          <span class="stat-item" title="点赞数">
                            <like-outlined />
                            {{ formatNumber(article.like_count) }}
                          </span>
                          <span class="stat-item" title="评论数">
                            <message-outlined />
                            {{ formatNumber(article.comment_count) }}
                          </span>
                        </div>
                      </div>
                      <time class="favorite-time">收藏于 {{ article.favorited_at }}</time>
                    </div>
                  </div>
                  <div class="article-cover" v-if="article.cover_image">
                    <img :src="getImageUrl(article.cover_image)" :alt="article.title" />
                  </div>
                </article>
              </div>
            </a-spin>
          </div>

          <!-- 粉丝列表 -->
          <div v-if="activeView === 'followers'" class="view-content">
            <!-- 粉丝列表头部 -->
            <div class="list-header">
              <h3>{{ isOwnProfile ? '我的粉丝' : `${userProfile.username || 'Ta'}的粉丝` }}</h3>
              <div class="list-actions">
                <a-button type="default" @click="refreshFollowersList" :icon="h(ReloadOutlined)">刷新</a-button>
              </div>
            </div>

            <a-spin :spinning="followersLoading">
              <div v-if="followers.length === 0 && !followersLoading" class="empty-state">
                <a-empty description="暂无粉丝">
                  <template #image>
                    <team-outlined style="font-size: 64px; color: #d9d9d9" />
                  </template>
                </a-empty>
              </div>
              <div v-else class="user-list">
                <div v-for="user in followers" :key="user.id" class="user-card">
                  <div class="user-main-info">
                    <a-avatar :size="50" :src="user.avatar ? getImageUrl(user.avatar) : ''" :style="{ backgroundColor: 'transparent' }">
                      {{ user.username?.charAt(0)?.toUpperCase() || 'U' }}
                    </a-avatar>
                    <div class="user-info">
                      <h4 class="user-name" @click.stop="handleUserNameClick(user.id)">{{ user.username }}</h4>
                      <p class="user-bio" v-if="user.bio">{{ user.bio }}</p>
                      <time class="follow-time">{{ formatDate(user.followed_at) }} 关注了你</time>
                    </div>
                  </div>
                  <div class="user-actions" v-if="userStore.isAuthenticated && user.id !== userStore.user?.userId">
                    <a-button v-if="!user.isFollowing" type="primary" :loading="user.followLoading" @click="handleFollowUser(user)"> 关注他 </a-button>
                    <a-button v-else type="default" :loading="user.followLoading" @click="handleUnfollowUser(user)"> 取消关注 </a-button>
                  </div>
                </div>

                <!-- 粉丝列表加载更多状态 -->
                <div class="load-more-status" v-if="followers.length > 0">
                  <div v-if="followersLoadingMore" class="loading-more">
                    <a-spin size="small" />
                    <span>加载中...</span>
                  </div>
                  <div v-else-if="!followersPagination.hasNext" class="no-more">
                    <span>没有更多粉丝了</span>
                    <div class="total-info">共 {{ followersPagination.total }} 位粉丝</div>
                  </div>
                </div>
              </div>
            </a-spin>
          </div>

          <!-- 关注列表 -->
          <div v-if="activeView === 'following'" class="view-content">
            <!-- 关注列表头部 -->
            <div class="list-header">
              <h3>{{ isOwnProfile ? '我的关注' : `${userProfile.username || 'Ta'}的关注` }}</h3>
              <div class="list-actions">
                <a-button type="default" @click="refreshFollowingList" :icon="h(ReloadOutlined)">刷新</a-button>
              </div>
            </div>

            <a-spin :spinning="followingLoading">
              <div v-if="following.length === 0 && !followingLoading" class="empty-state">
                <a-empty description="暂无关注">
                  <template #image>
                    <user-add-outlined style="font-size: 64px; color: #d9d9d9" />
                  </template>
                </a-empty>
              </div>
              <div v-else class="user-list">
                <div v-for="user in following" :key="user.id" class="user-card">
                  <div class="user-main-info">
                    <a-avatar :size="50" :src="user.avatar ? getImageUrl(user.avatar) : ''" :style="{ backgroundColor: 'transparent' }">
                      {{ user.username?.charAt(0)?.toUpperCase() || 'U' }}
                    </a-avatar>
                    <div class="user-info">
                      <h4 class="user-name" @click.stop="handleUserNameClick(user.id)">{{ user.username }}</h4>
                      <p class="user-bio" v-if="user.bio">{{ user.bio }}</p>
                      <time class="follow-time">{{ formatDate(user.followed_at) }} 关注</time>
                    </div>
                  </div>
                  <div class="user-actions" v-if="userStore.isAuthenticated && user.id !== userStore.user?.userId">
                    <a-button type="default" :loading="user.followLoading" @click="handleUnfollowUser(user)">取消关注</a-button>
                  </div>
                </div>

                <!-- 关注列表加载更多状态 -->
                <div class="load-more-status" v-if="following.length > 0">
                  <div v-if="followingLoadingMore" class="loading-more">
                    <a-spin size="small" />
                    <span>加载中...</span>
                  </div>
                  <div v-else-if="!followingPagination.hasNext" class="no-more">
                    <span>没有更多关注了</span>
                    <div class="total-info">共 {{ followingPagination.total }} 位关注</div>
                  </div>
                </div>
              </div>
            </a-spin>
          </div>

          <!-- 通知列表 -->
          <div v-if="activeView === 'notifications'" class="view-content">
            <div class="notifications-header">
              <h3>消息通知</h3>
              <a-button-group>
                <a-button @click="markAllAsRead" :disabled="unreadCount === 0">全部已读</a-button>
              </a-button-group>
            </div>

            <a-spin :spinning="notificationsLoading">
              <div v-if="notifications.length === 0 && !notificationsLoading" class="empty-state">
                <a-empty description="暂无通知">
                  <template #image>
                    <bell-outlined style="font-size: 64px; color: #d9d9d9" />
                  </template>
                </a-empty>
              </div>
              <div v-else class="notifications-list">
                <div v-for="notification in notifications" :key="notification.id" class="notification-item" :class="{ unread: !notification.is_read }" @click="handleNotificationClick(notification)">
                  <div class="notification-avatar">
                    <div class="avatar-container">
                      <a-avatar v-if="notification.from_avatar" :size="40" :src="getImageUrl(notification.from_avatar)">
                        {{ notification.from_username?.charAt(0)?.toUpperCase() || 'S' }}
                      </a-avatar>
                      <a-avatar v-else :size="40" :style="{ backgroundColor: '#1890ff' }">
                        {{ notification.from_username?.charAt(0)?.toUpperCase() || 'S' }}
                      </a-avatar>
                      <div class="notification-type-badge" :class="getTypeClass(notification.type)">
                        <component :is="getTypeIcon(notification.type)" />
                      </div>
                    </div>
                  </div>
                  <div class="notification-content">
                    <h4 class="notification-title">{{ notification.title }}</h4>
                    <p class="notification-text">{{ notification.content }}</p>
                    <time class="notification-time">{{ formatDate(notification.created_at) }}</time>
                  </div>
                  <div class="notification-actions">
                    <a-button v-if="!notification.is_read" type="link" size="small" @click.stop="markAsRead(notification.id)"> 标记已读 </a-button>
                  </div>
                </div>

                <!-- 通知列表加载更多状态 -->
                <div class="load-more-status" v-if="notifications.length > 0">
                  <div v-if="notificationsLoadingMore" class="loading-more">
                    <a-spin size="small" />
                    <span>加载中...</span>
                  </div>
                  <div v-else-if="!notificationsPagination.hasNext" class="no-more">
                    <span>没有更多通知了</span>
                    <div class="total-info">共 {{ notificationsPagination.total }} 条通知</div>
                  </div>
                </div>
              </div>
            </a-spin>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, h, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { EditOutlined, SaveOutlined, FileTextOutlined, StarOutlined, UserOutlined, EyeOutlined, LikeOutlined, MessageOutlined, TeamOutlined, UserAddOutlined, BellOutlined, UploadOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'
import { getImageUrl } from '@/utils/image'
import UserStatsChart from '@/components/UserStatsChart.vue'
import AuthorHover from '@/components/AuthorHover.vue'
import dayjs from 'dayjs'
import { API_BASE_URL } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeView = ref('profile')
const selectedMenuKeys = ref(['profile'])
const userInfo = ref({})
const userStats = ref({})
const userProfile = ref({})
const followStats = ref({})
const followStatus = ref({})
const followLoading = ref(false)
const unreadCount = ref(0)

// 编辑相关
const isEditing = ref(false)
const editForm = ref({
  username: '',
  bio: '',
  avatar: '',
  career_direction: '',
  position: '',
  company: '',
  work_start_date: null,
  interest_tags: []
})

// 文章相关
const articles = ref([])
const articlesLoading = ref(false)
const articlesLoadingMore = ref(false)
const articlesPagination = ref({
  page: 1,
  limit: 10,
  total: 0,
  hasNext: false
})

// 收藏相关
const favorites = ref([])
const favoritesLoading = ref(false)
const favoritesPagination = ref({
  page: 1,
  limit: 10,
  total: 0,
  hasNext: false
})

// 关注/粉丝相关
const followers = ref([])
const following = ref([])
const followersLoading = ref(false)
const followingLoading = ref(false)
const followersLoadingMore = ref(false)
const followingLoadingMore = ref(false)
const followersPagination = ref({
  page: 1,
  limit: 20,
  total: 0,
  hasNext: false
})
const followingPagination = ref({
  page: 1,
  limit: 20,
  total: 0,
  hasNext: false
})

// 通知相关
const notifications = ref([])
const notificationsLoading = ref(false)
const notificationsLoadingMore = ref(false)
const notificationsPagination = ref({
  page: 1,
  limit: 20,
  total: 0,
  hasNext: false
})

// 滚动容器引用
const userCenterContainer = ref(null)

// 计算属性
const userId = computed(() => route.params.id || userStore.user?.userId)
const isOwnProfile = computed(() => {
  return userStore.isAuthenticated && (!route.params.id || userStore.user?.userId === parseInt(route.params.id))
})

// 记录退出登录时是否在自己的主页
const wasOwnProfileBeforeLogout = ref(false)

// 检查是否是未登录状态下访问自己的主页
const isAccessingOwnProfileWhileLoggedOut = computed(() => {
  return !userStore.isAuthenticated && (!route.params.id || wasOwnProfileBeforeLogout.value)
})

// 判断是否有工作信息
const hasWorkInfo = computed(() => {
  return userProfile.value.career_direction || userProfile.value.position || userProfile.value.company || userProfile.value.work_start_date
})

// 判断是否有任何个人资料信息
const hasAnyProfile = computed(() => {
  return userProfile.value.bio || (userProfile.value.interest_tags && userProfile.value.interest_tags.length > 0) || hasWorkInfo.value
})

// API 调用函数
const fetchUserInfo = async () => {
  if (!userId.value) return
  
  try {
    const headers = {}
    if (getToken()) {
      headers.Authorization = `Bearer ${getToken()}`
    }

    const response = await fetch(`${API_BASE_URL}/auth/profile/${userId.value}`, { headers })
    const result = await response.json()

    if (result.code === 200) {
      userInfo.value = result.data
      userProfile.value = result.data
    } else {
      console.error('获取用户信息失败:', result.msg)
      message.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    message.error('网络错误，请稍后重试')
  }
}

const fetchUserStats = async () => {
  if (!userId.value) return
  
  try {
    const response = await fetch(`${API_BASE_URL}/articles/user/${userId.value}/stats`)
    const result = await response.json()

    if (result.code === 200) {
      userStats.value = {
        ...result.data,
        trendData: result.data.trendData || []
      }
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

const fetchFollowStats = async () => {
  if (!userId.value) return
  
  try {
    const response = await fetch(`${API_BASE_URL}/follows/user/${userId.value}/stats`)
    const result = await response.json()

    if (result.code === 200) {
      followStats.value = result.data
    }
  } catch (error) {
    console.error('获取关注统计失败:', error)
  }
}

const fetchFollowStatus = async () => {
  if (!userId.value || !userStore.isAuthenticated || isOwnProfile.value) return

  try {
    const response = await fetch(`${API_BASE_URL}/follows/check/${userId.value}`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      followStatus.value = result.data
    }
  } catch (error) {
    console.error('获取关注状态失败:', error)
  }
}

const fetchUserArticles = async (page = 1, append = false) => {
  if (!userId.value) return
  
  if (page === 1) {
    articlesLoading.value = true
  } else {
    articlesLoadingMore.value = true
  }

  try {
    const response = await fetch(`${API_BASE_URL}/articles/user/${userId.value}/articles?page=${page}&limit=${articlesPagination.value.limit}`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      const newArticles = result.data.list || []

      if (append) {
        articles.value.push(...newArticles)
      } else {
        articles.value = newArticles
      }

      articlesPagination.value = { ...articlesPagination.value, ...result.data.pagination }
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
  } finally {
    articlesLoading.value = false
    articlesLoadingMore.value = false
  }
}

const fetchUserFavorites = async () => {
  if (!userId.value || !isOwnProfile.value) return

  favoritesLoading.value = true
  try {
    const response = await fetch(`${API_BASE_URL}/articles/user/${userId.value}/favorites?page=1&limit=20`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      favorites.value = result.data.list || []
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
  } finally {
    favoritesLoading.value = false
  }
}

const refreshFavorites = async () => {
  if (!isOwnProfile.value) return
  await fetchUserFavorites()
}

const refreshFollowersList = async () => {
  await fetchFollowers(1, false)
}

const refreshFollowingList = async () => {
  await fetchFollowing(1, false)
}

const fetchFollowers = async (page = 1, append = false) => {
  if (!userId.value) return
  
  if (page === 1) {
    followersLoading.value = true
  } else {
    followersLoadingMore.value = true
  }

  try {
    const response = await fetch(`${API_BASE_URL}/follows/user/${userId.value}/followers?page=${page}&limit=${followersPagination.value.limit}`)
    const result = await response.json()

    if (result.code === 200) {
      const followersList = result.data.list || []

      // 为每个粉丝检查关注状态
      if (userStore.isAuthenticated) {
        for (const follower of followersList) {
          try {
            const statusResponse = await fetch(`/api/follows/check/${follower.id}`, {
              headers: {
                Authorization: `Bearer ${getToken()}`
              }
            })
            const statusResult = await statusResponse.json()
            follower.isFollowing = statusResult.code === 200 ? statusResult.data.isFollowing : false
            follower.followLoading = false
          } catch (error) {
            follower.isFollowing = false
            follower.followLoading = false
          }
        }
      }

      if (append) {
        followers.value.push(...followersList)
      } else {
        followers.value = followersList
      }

      followersPagination.value = { ...followersPagination.value, ...result.data.pagination }
    }
  } catch (error) {
    console.error('获取粉丝列表失败:', error)
  } finally {
    followersLoading.value = false
    followersLoadingMore.value = false
  }
}

const fetchFollowing = async (page = 1, append = false) => {
  if (!userId.value) return
  
  if (page === 1) {
    followingLoading.value = true
  } else {
    followingLoadingMore.value = true
  }

  try {
    const response = await fetch(`${API_BASE_URL}/follows/user/${userId.value}/following?page=${page}&limit=${followingPagination.value.limit}`)
    const result = await response.json()

    if (result.code === 200) {
      const followingList = result.data.list || []

      // 为关注列表中的每个用户添加loading状态
      followingList.forEach((user) => {
        user.isFollowing = true // 关注列表中的用户都是已关注的
        user.followLoading = false
      })

      if (append) {
        following.value.push(...followingList)
      } else {
        following.value = followingList
      }

      followingPagination.value = { ...followingPagination.value, ...result.data.pagination }
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
  } finally {
    followingLoading.value = false
    followingLoadingMore.value = false
  }
}

const fetchNotifications = async (page = 1, append = false) => {
  if (!isOwnProfile.value) return

  if (page === 1) {
    notificationsLoading.value = true
  } else {
    notificationsLoadingMore.value = true
  }

  try {
    const response = await fetch(`${API_BASE_URL}/notifications/list?page=${page}&limit=${notificationsPagination.value.limit}`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      const newNotifications = result.data.list || []

      if (append) {
        notifications.value.push(...newNotifications)
      } else {
        notifications.value = newNotifications
      }

      notificationsPagination.value = { ...notificationsPagination.value, ...result.data.pagination }
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
  } finally {
    notificationsLoading.value = false
    notificationsLoadingMore.value = false
  }
}

const fetchUnreadCount = async () => {
  if (!isOwnProfile.value) return

  try {
    const response = await fetch(`${API_BASE_URL}/notifications/unread-count`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      unreadCount.value = result.data.totalUnread || 0
    }
  } catch (error) {
    console.error('获取未读通知数失败:', error)
  }
}

// 事件处理函数
const handleMenuSelect = ({ key }) => {
  activeView.value = key
  selectedMenuKeys.value = [key]

  // 根据选择的菜单项加载对应数据
  switch (key) {
    case 'articles':
      if (articles.value.length === 0) {
        fetchUserArticles()
      }
      break
    case 'favorites':
      if (favorites.value.length === 0) {
        fetchUserFavorites()
      }
      break
    case 'followers':
      if (followers.value.length === 0) {
        fetchFollowers()
      }
      break
    case 'following':
      if (following.value.length === 0) {
        fetchFollowing()
      }
      break
    case 'notifications':
      if (notifications.value.length === 0) {
        fetchNotifications()
      }
      break
  }
}

const handleFollowToggle = async () => {
  if (!userId.value || !userStore.isAuthenticated) {
    message.error('请先登录')
    return
  }

  followLoading.value = true
  try {
    const url = followStatus.value.isFollowing ? `${API_BASE_URL}/follows/unfollow/${userId.value}` : `${API_BASE_URL}/follows/follow/${userId.value}`

    const method = followStatus.value.isFollowing ? 'DELETE' : 'POST'

    const response = await fetch(url, {
      method,
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      followStatus.value.isFollowing = !followStatus.value.isFollowing
      // 更新粉丝数
      followStats.value.followersCount += followStatus.value.isFollowing ? 1 : -1
      message.success(result.msg)
    } else {
      message.error(result.msg)
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    message.error('操作失败，请稍后重试')
  } finally {
    followLoading.value = false
  }
}

const handleWriteArticle = () => {
  router.push('/articles/write')
}

const toggleEditMode = () => {
  if (isEditing.value) {
    saveProfile()
  } else {
    // 进入编辑模式，填充表单数据
    editForm.value = {
      username: userProfile.value.username || '',
      bio: userProfile.value.bio || '',
      avatar: userProfile.value.avatar || '',
      career_direction: userProfile.value.career_direction || '',
      position: userProfile.value.position || '',
      company: userProfile.value.company || '',
      work_start_date: userProfile.value.work_start_date ? dayjs(userProfile.value.work_start_date) : null,
      interest_tags: userProfile.value.interest_tags || []
    }
    isEditing.value = true
  }
}

const cancelEdit = () => {
  isEditing.value = false
  editForm.value = {
    username: '',
    bio: '',
    avatar: '',
    career_direction: '',
    position: '',
    company: '',
    work_start_date: null,
    interest_tags: []
  }
}

const saveProfile = async () => {
  try {
    const payload = {
      ...editForm.value,
      work_start_date: editForm.value.work_start_date ? editForm.value.work_start_date.format('YYYY-MM-DD') : null
    }

    const response = await fetch(`${API_BASE_URL}/auth/profile`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`
      },
      body: JSON.stringify(payload)
    })

    const result = await response.json()

    if (result.code === 200) {
      message.success('个人资料更新成功')
      // 更新本地数据
      Object.assign(userProfile.value, result.data)
      isEditing.value = false

      // 重新获取用户信息
      await fetchUserInfo()
    } else {
      message.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    message.error('网络错误，请稍后重试')
  }
}

const handleEditProfile = toggleEditMode

// 头像上传处理函数
const handleAvatarUpload = async (file) => {
  const formData = new FormData()
  formData.append('image', file)

  try {
    const response = await fetch(`${API_BASE_URL}/upload/avatar`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      body: formData
    })

    const result = await response.json()

    if (result.code === 200) {
      editForm.value.avatar = result.data.path
      message.success('头像上传成功')
      return true
    } else {
      message.error(result.msg || '头像上传失败')
      return false
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    message.error('头像上传失败，请稍后重试')
    return false
  }
}

const removeAvatar = () => {
  editForm.value.avatar = ''
  message.success('头像已移除')
}

const handleArticleClick = (articleId) => {
  router.push(`/articles/${articleId}`)
}

const handleUserNameClick = (userId) => {
  window.open(`/user/${userId}`, '_blank')
}

const handleFollowUser = async (user) => {
  if (!userStore.isAuthenticated) {
    message.error('请先登录')
    return
  }

  user.followLoading = true
  try {
    const response = await fetch(`${API_BASE_URL}/follows/follow/${user.id}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      user.isFollowing = true
      message.success('关注成功')
      // 更新关注统计
      followStats.value.followingCount = (followStats.value.followingCount || 0) + 1
    } else {
      message.error(result.msg)
    }
  } catch (error) {
    console.error('关注失败:', error)
    message.error('操作失败，请稍后重试')
  } finally {
    user.followLoading = false
  }
}

const handleUnfollowUser = async (user) => {
  if (!userStore.isAuthenticated) {
    message.error('请先登录')
    return
  }

  user.followLoading = true
  try {
    const response = await fetch(`${API_BASE_URL}/follows/unfollow/${user.id}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      user.isFollowing = false
      message.success('取消关注成功')
      // 更新关注统计
      followStats.value.followingCount = Math.max(0, (followStats.value.followingCount || 0) - 1)
      // 从关注列表中移除该用户
      if (activeView.value === 'following') {
        const index = following.value.findIndex((f) => f.id === user.id)
        if (index > -1) {
          following.value.splice(index, 1)
        }
      }
    } else {
      message.error(result.msg)
    }
  } catch (error) {
    console.error('取消关注失败:', error)
    message.error('操作失败，请稍后重试')
  } finally {
    user.followLoading = false
  }
}

const handleOpenLogin = () => {
  // 触发全局登录事件
  window.dispatchEvent(new CustomEvent('openLogin'))
}

const handleNotificationClick = async (notification) => {
  if (!notification.is_read) {
    await markAsRead(notification.id)
  }

  // 根据通知类型跳转到相应页面
  if (notification.related_type === 'article' && notification.related_id) {
    router.push(`/articles/${notification.related_id}`)
  }
}

const markAsRead = async (notificationId) => {
  try {
    const response = await fetch(`${API_BASE_URL}/notifications/${notificationId}/read`, {
      method: 'PUT',
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })

    if (response.ok) {
      // 更新本地状态
      const notification = notifications.value.find((n) => n.id === notificationId)
      if (notification) {
        notification.is_read = true
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

const markAllAsRead = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/notifications/mark-read`, {
      method: 'PUT',
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })

    if (response.ok) {
      notifications.value.forEach((n) => (n.is_read = true))
      unreadCount.value = 0
      message.success('全部标记为已读')
    }
  } catch (error) {
    console.error('批量标记已读失败:', error)
  }
}

// 获取通知类型图标
const getTypeIcon = (type) => {
  switch (type) {
    case 'article_like':
      return 'LikeOutlined'
    case 'comment_like':
      return 'LikeOutlined'
    case 'article_comment':
      return 'MessageOutlined'
    case 'comment_reply':
      return 'MessageOutlined'
    case 'follow':
      return 'UserAddOutlined'
    default:
      return 'BellOutlined'
  }
}

// 获取通知类型样式类名
const getTypeClass = (type) => {
  switch (type) {
    case 'article_like':
    case 'comment_like':
      return 'type-like'
    case 'article_comment':
    case 'comment_reply':
      return 'type-comment'
    case 'follow':
      return 'type-follow'
    default:
      return 'type-default'
  }
}

// 格式化函数
const formatNumber = (num) => {
  if (!num) return '0'
  if (num < 1000) return num.toString()
  if (num < 10000) return (num / 1000).toFixed(1) + 'k'
  return (num / 10000).toFixed(1) + 'w'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  return dayjs(dateStr).format('YYYY年MM月DD日')
}

// 加载更多函数
const loadMoreArticles = async () => {
  if (articlesLoadingMore.value || !articlesPagination.value.hasNext) return
  articlesLoadingMore.value = true
  await fetchUserArticles(articlesPagination.value.page + 1, true)
  articlesLoadingMore.value = false
}

const loadMoreFollowers = async () => {
  if (followersLoadingMore.value || !followersPagination.value.hasNext) return
  await fetchFollowers(followersPagination.value.page + 1, true)
}

const loadMoreFollowing = async () => {
  if (followingLoadingMore.value || !followingPagination.value.hasNext) return
  await fetchFollowing(followingPagination.value.page + 1, true)
}

const loadMoreNotifications = async () => {
  if (notificationsLoadingMore.value || !notificationsPagination.value.hasNext) return
  await fetchNotifications(notificationsPagination.value.page + 1, true)
}

// 滚动监听函数
const handleScroll = () => {
  if (!userCenterContainer.value) return

  const container = userCenterContainer.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight

  // 当滚动到距离底部100px时触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    switch (activeView.value) {
      case 'articles':
        loadMoreArticles()
        break
      case 'followers':
        loadMoreFollowers()
        break
      case 'following':
        loadMoreFollowing()
        break
      case 'notifications':
        loadMoreNotifications()
        break
    }
  }
}

// 初始化数据
const initPageData = async () => {
  // 如果在/user路由下但未登录，不需要获取数据，直接显示登录提示
  if (!route.params.id && !userStore.isAuthenticated) {
    return
  }
  
  // 如果没有有效的userId，说明用户不存在或数据异常
  if (!userId.value) {
    message.error('用户不存在')
    router.push('/articles')
    return
  }

  // 检查URL参数设置默认视图
  const viewParam = route.query.view
  if (viewParam && ['profile', 'articles', 'favorites', 'followers', 'following', 'notifications'].includes(viewParam)) {
    activeView.value = viewParam
    selectedMenuKeys.value = [viewParam]
  }

  await Promise.all([fetchUserInfo(), fetchUserStats(), fetchFollowStats(), fetchFollowStatus(), fetchUnreadCount()])
}

// 监听路由参数变化
watch(
  () => route.params.id,
  (newUserId, oldUserId) => {
    if (newUserId !== oldUserId) {
      // 路由切换时清除退出登录前的状态记录
      wasOwnProfileBeforeLogout.value = false
      initPageData()
    }
  }
)

// 监听路由查询参数变化
watch(
  () => route.query.view,
  (newView) => {
    if (newView && ['profile', 'articles', 'favorites', 'followers', 'following', 'notifications'].includes(newView)) {
      activeView.value = newView
      selectedMenuKeys.value = [newView]
    }
  }
)

// 监听用户登录状态变化
watch(
  () => userStore.isAuthenticated,
  (newAuth, oldAuth) => {
    if (oldAuth && !newAuth) {
      // 从登录状态变为未登录状态（退出登录）
      // 记录退出登录前是否在自己的主页
      wasOwnProfileBeforeLogout.value = isOwnProfile.value
      
      // 如果当前访问的是自己的主页，清除所有数据
      if (isOwnProfile.value) {
        userProfile.value = {}
        userStats.value = {}
        followStats.value = {}
        articles.value = []
        favorites.value = []
        followers.value = []
        following.value = []
        notifications.value = []
        unreadCount.value = 0
      }
    } else if (!oldAuth && newAuth) {
      // 从未登录状态变为登录状态（登录）
      // 清除退出登录前的状态记录
      wasOwnProfileBeforeLogout.value = false
      
      // 重新初始化数据
      initPageData()
    }
  }
)

// 页面加载
onMounted(async () => {
  await initPageData()

  // 添加滚动监听
  if (userCenterContainer.value) {
    userCenterContainer.value.addEventListener('scroll', handleScroll)
  }
})

// 页面卸载时移除监听器
onBeforeUnmount(() => {
  if (userCenterContainer.value) {
    userCenterContainer.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
@import './center.css';
</style>
